package Pet.Management.service;

import Pet.Management.domain.dto.UserDataDTO;
import Pet.Management.domain.entity.User;
import Pet.Management.repository.UserRepository;
import Pet.Management.repository.PetCareAcceptorRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserDataService {

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PetCareAcceptorRepository acceptorRepository;

    public Page<UserDataDTO> getUserList(String keyword, String authStatus, Pageable pageable) {
        Page<User> userPage;
        
        if (keyword != null && !keyword.isEmpty()) {
            // 根据关键词搜索
            userPage = userRepository.findByPhoneContainingOrUsernameContaining(keyword, keyword, pageable);
        } else if (authStatus != null && !authStatus.isEmpty()) {
            // 根据实名状态筛选
            boolean isAuth = "1".equals(authStatus);
            userPage = userRepository.findByIdCardIsNotNull(isAuth, pageable);
        } else {
            // 获取所有用户
            userPage = userRepository.findAll(pageable);
        }

        List<UserDataDTO> userDataDTOs = userPage.getContent().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());

        return new PageImpl<>(userDataDTOs, pageable, userPage.getTotalElements());
    }

    private UserDataDTO convertToDTO(User user) {
        UserDataDTO dto = new UserDataDTO();
        dto.setUserId(user.getId());
        dto.setUserName(user.getUsername());
        dto.setSex(user.getSex() == null ? "0" : user.getSex().toString());
        dto.setIdCard(user.getIdCard());
        dto.setPhonenumber(user.getPhone());
        dto.setCreateTime(user.getCreateTime());
        dto.setAuthStatus(user.getIdCard() != null ? "1" : "0");
        
        // 获取用户关联的宠物类型（从接单者表）
        acceptorRepository.findByUserId(user.getId())
                .ifPresent(acceptor -> dto.setPetType(acceptor.getGoodAtPetType()));
        
        // 设置订单数量（这里暂时设置为0，后续可以根据实际订单表统计）
        dto.setOrderCount(0);
        
        return dto;
    }
} 